<template>
  <div class="carousel-management">
    <!-- 页面标题和操作区 -->
    <el-row :gutter="20" class="page-header">
      <el-col :span="12">
        <el-page-header @back="handleBack" content="轮播图管理" class="page-title"></el-page-header>
      </el-col>
      <el-col :span="12" class="text-right">
        <el-button type="primary" icon="el-icon-plus" @click="showAddModal = true" :loading="loading" size="mini">
          新增轮播图
        </el-button>
      </el-col>
    </el-row>

    <!-- 轮播图列表 -->
    <el-card class="carousel-list-card" shadow="hover">
      <el-table :data="carousels" border stripe :loading="loading" :row-class-name="tableRowClassName"
        @row-click="handleRowClick">

        <el-table-column label="轮播图预览" align="center" prop="configValue" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.configValue" :width="50" :height="50" />
          </template>

        </el-table-column>

        <el-table-column prop="configName" align="center" label="标题" width="180"></el-table-column>


        <el-table-column prop="sortOrder" label="排序" width="80" align="center"></el-table-column>

        <el-table-column label="操作" width="140" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" size="mini"
              title="编辑"></el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row.configId)" size="mini"
              title="删除" class="text-danger"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="empty" class="empty-state">
        <el-empty description="暂无轮播图数据" :image="emptyImage">
          <el-button type="primary" icon="el-icon-plus" @click="showAddModal = true" slot="bottom">
            添加第一张轮播图
          </el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 轮播图预览 -->
    <el-card class="preview-card" shadow="hover" style="margin-top: 20px;">
      <div slot="header" class="preview-header">
        <span>轮播图预览</span>
      </div>

      <el-carousel :interval="5000" :height="carouselHeight" :initial-index="0" indicator-position="outside"
        arrow="always" @change="handleCarouselChange" v-if="carousels.length > 0">
        <el-carousel-item v-for="(item, index) in carousels" :key="index">
          <image-preview :src="item.configValue" :alt="item.configName" class="carousel-preview-image" fit="cover">
          </image-preview>   
        </el-carousel-item>
      </el-carousel>

      <div v-else class="no-preview">
        <el-empty description="暂无轮播图可预览"></el-empty>
      </div>
    </el-card>

    <!-- 新增/编辑轮播图弹窗 -->
    <el-dialog :title="isEditing ? '编辑轮播图' : '新增轮播图'" :visible.sync="showModal" :width="dialogWidth"
      :close-on-click-modal="false" :before-close="handleDialogClose">
      <el-form :model="formData" :rules="formRules" ref="carouselForm" label-width="100px" :disabled="submitting">
        <el-form-item label="标题" prop="configName">
          <el-input v-model="formData.configName" placeholder="请输入轮播图标题" clearable></el-input>
        </el-form-item>


        <el-form-item label="轮播图" prop="configValue">
          <image-upload v-model="formData.configValue" />
        </el-form-item>

        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="1" :step="1" placeholder="数字越小越靠前"></el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose" :loading="submitting">
          取消
        </el-button>
        <el-button type="primary" @click="saveCarousel" :loading="submitting">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCarousel,
  getCarousel,
  addCarousel,
  updateCarousel,
  delCarousel
} from "@/api/carousel/carousel"

export default {
  name: 'CarouselManagement',
  data() {
    // 表单验证规则
    const validateUrl = (rule, value, callback) => {
      if (value) {
        try {
          new URL(value);
          callback();
        } catch (e) {
          callback(new Error('请输入有效的URL地址'));
        }
      } else {
        callback();
      }
    };

    return {
      // 轮播图数据
      carousels: [],
      loading: false,

      // 弹窗状态
      showAddModal: false,
      showModal: false,
      isEditing: false,
      dialogWidth: '600px',

      // 表单数据
      formData: {
        configId: null,
        configName: '',
        configValue: '',
        sortOrder: 1
      },

      // 表单验证规则
      formRules: {
        configName: [
          { required: true, message: '请输入轮播图标题', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' },
          { type: 'number', min: 1, message: '排序号不能小于1', trigger: 'blur' }
        ]
      },

      // 操作状态
      submitting: false,

      // 使用Element UI提供的空状态图片
      emptyImage: 'https://cube.elemecdn.com/6/94/4d3ea53c0c954564a0d2c7589a4jpeg.jpeg',

      // 轮播高度
      carouselHeight: '400px',

      // 用于动画效果
      currentRowIndex: -1
    };
  },

  mounted() {
    // 加载轮播图数据
    this.loadCarousels();

    // 监听窗口大小变化，调整轮播高度
    window.addEventListener('resize', this.handleResize);
    this.handleResize();
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },

  watch: {
    // 当新增弹窗显示时，打开表单弹窗
    showAddModal(newVal) {
      if (newVal) {
        this.isEditing = false;
        this.resetForm();
        this.showModal = true;
      }
    },

    // 当轮播图数据变化时，按排序号排序
    /* carousels(newVal) {
      if (newVal && newVal.length > 0) {
        newVal.sort((a, b) => a.sortOrder - b.sortOrder);
      }
    } */
  },

  methods: {
    // 返回上一页
    handleBack() {
      this.$router.go(-1);
    },

    // 加载轮播图列表
    loadCarousels() {
      this.loading = true;
      listCarousel()
        .then(response => {
          this.loading = false;
          // 假设接口返回格式为 { code: 200, data: [...] }
          if (response.code === 200) {
            this.carousels = response.data.sort((a, b) => {
              // 注意：确保对象中有 sortOrder 属性，否则使用默认值
              return (a.sortOrder || 0) - (b.sortOrder || 0);
            });
            console.log(this.carousels)
          } else {
            this.$message.error('加载轮播图失败: ' + (response.msg || '未知错误'));
          }
        })
        .catch(error => {
          console.error('加载轮播图出错:', error);
          this.$message.error('加载轮播图时发生错误');
          this.loading = false;
        });
    },

    // 编辑轮播图
    handleEdit(item) {
      this.isEditing = true;
      this.loading = true;

      getCarousel(item.configId)
        .then(response => {
          this.loading = false;
          if (response.code === 200) {
            this.formData = { ...response.data };
            this.showModal = true;
          } else {
            this.$message.error('获取轮播图详情失败: ' + (response.msg || '未知错误'));
          }
        })
        .catch(error => {
          console.error('获取轮播图详情出错:', error);
          this.$message.error('获取轮播图详情时发生错误');
          this.loading = false;
        });
    },

    // 处理删除
    handleDelete(configId) {
      this.$confirm('确定要删除这张轮播图吗？此操作不可撤销。', '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitting = true;
        delCarousel(configId)
          .then(response => {
            this.submitting = false;
            if (response.code === 200) {
              this.$message.success('轮播图已成功删除');
              this.loadCarousels();
            } else {
              this.$message.error('删除轮播图失败: ' + (response.msg || '未知错误'));
            }
          })
          .catch(error => {
            console.error('删除轮播图出错:', error);
            this.$message.error('删除轮播图时发生错误');
            this.submitting = false;
          });
      }).catch(() => {
        // 取消删除
        this.$message.info('已取消删除');
      });
    },

    // 关闭弹窗
    handleDialogClose() {
      this.showModal = false;
      this.showAddModal = false;
      this.$nextTick(() => {
        this.resetForm();
      });
    },

    // 重置表单
    resetForm() {
      if (this.$refs.carouselForm) {
        this.$refs.carouselForm.resetFields();
      }
      this.formData = {
        configId: null,
        configName: '',
        configValue: '',
        sortOrder: 1
      };
      this.isEditing = false;
      this.submitting = false;
    },

    // 保存轮播图
    saveCarousel() {
      this.$refs.carouselForm.validate(valid => {
        if (valid) {
          this.submitting = true;

          const requestFn = this.isEditing ? updateCarousel : addCarousel;

          requestFn(this.formData)
            .then(response => {
              this.submitting = false;

              if (response.code === 200) {
                this.$message.success(
                  this.isEditing ? '轮播图已成功更新' : '轮播图已成功添加'
                );
                this.handleDialogClose();
                this.loadCarousels();
              } else {
                this.$message.error(
                  (this.isEditing ? '更新' : '添加') + '轮播图失败: ' + (response.msg || '未知错误')
                );
              }
            })
            .catch(error => {
              console.error((this.isEditing ? '更新' : '添加') + '轮播图出错:', error);
              this.$message.error(
                (this.isEditing ? '更新' : '添加') + '轮播图时发生错误'
              );
              this.submitting = false;
            });
        }
      });
    },


    // 处理轮播图切换
    handleCarouselChange(index) {
      console.log('当前轮播索引: ' + index);
    },

    // 表格行样式
    tableRowClassName({ row, rowIndex }) {
      return 'fade-in-row';
    },

    // 表格行点击
    handleRowClick(row, column, event) {
      // 可以在这里添加行点击事件逻辑
    },

    // 处理窗口大小变化
    handleResize() {
      // 在小屏幕上调整轮播高度
      if (window.innerWidth < 768) {
        this.carouselHeight = '250px';
        this.dialogWidth = '90%';
      } else {
        this.carouselHeight = '400px';
        this.dialogWidth = '600px';
      }
    }
  }
};
</script>

<style scoped>
.carousel-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-title>>>.el-page-header__content {
  font-size: 20px;
  font-weight: 500;
}

.carousel-list-card {
  margin-bottom: 20px;
}

.carousel-image {
  width: 100px;
  height: 60px;
  border-radius: 4px;
}

.image-error {
  width: 100px;
  height: 60px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0ccda;
}

.preview-card {
  margin-top: 20px;
}

.preview-header {
  font-weight: 500;
  font-size: 16px;
}

.carousel-preview-image {
  width: 100%;
  height: 100%;
}

.preview-image-error {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0ccda;
  font-size: 32px;
}

.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 20px;
}

.carousel-caption h3 {
  margin: 0;
  font-size: 20px;
}

.form-image-preview {
  width: 100%;
  max-height: 200px;
  margin-top: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.form-image-error {
  width: 100%;
  height: 200px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0ccda;
  font-size: 32px;
}

.no-preview {
  padding: 50px 0;
}

.link-url {
  color: #409eff;
  text-decoration: none;
}

.link-url:hover {
  text-decoration: underline;
}

.empty-state>>>.el-empty__image {
  width: 120px;
  height: 120px;
}

/* 动画效果 */
.fade-in-row {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .carousel-management {
    padding: 10px;
  }

  .carousel-image {
    width: 80px;
    height: 48px;
  }

  .image-error {
    width: 80px;
    height: 48px;
  }
}
</style>
